"""
语音电话路由
处理语音电话相关的API端点
"""

from fastapi import APIRouter, WebSocket, Query, Path, Depends, HTTPException
from typing import Optional, List
import uuid
from src.services.voice_call_service import voice_call_service, voice_call_manager
from src.services.auth_service import get_current_active_user_dep as get_current_user
from src.utils.logging import get_logger

logger = get_logger(__name__)

router = APIRouter(prefix="/voice", tags=["语音电话"])

@router.post("/call/start")
async def start_voice_call(
    participants: List[str],
    current_user: dict = Depends(get_current_user)
):
    """
    开始语音通话
    
    Args:
        participants: 参与者用户ID列表
        current_user: 当前用户信息
        
    Returns:
        通话信息
    """
    try:
        # 生成唯一的通话ID
        call_id = str(uuid.uuid4())
        
        # 开始通话
        call_info = await voice_call_manager.start_call(
            call_id=call_id,
            initiator_id=current_user["user_id"],
            participants=participants
        )
        
        logger.info(f"用户 {current_user['user_id']} 发起语音通话: {call_id}")
        
        return {
            "success": True,
            "call_id": call_id,
            "call_info": call_info
        }
        
    except Exception as e:
        logger.error(f"开始语音通话失败: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"开始语音通话失败: {str(e)}")

@router.post("/call/{call_id}/end")
async def end_voice_call(
    call_id: str,
    current_user: dict = Depends(get_current_user)
):
    """
    结束语音通话
    
    Args:
        call_id: 通话ID
        current_user: 当前用户信息
        
    Returns:
        操作结果
    """
    try:
        call_info = voice_call_manager.get_call_info(call_id)
        if not call_info:
            raise HTTPException(status_code=404, detail="通话不存在")
        
        # 检查用户是否有权限结束通话
        if current_user["user_id"] not in call_info["connected_users"]:
            raise HTTPException(status_code=403, detail="无权限结束此通话")
        
        # 结束通话
        voice_call_manager.end_call(call_id)
        
        logger.info(f"用户 {current_user['user_id']} 结束语音通话: {call_id}")
        
        return {
            "success": True,
            "message": "通话已结束"
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"结束语音通话失败: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"结束语音通话失败: {str(e)}")

@router.get("/call/{call_id}/info")
async def get_call_info(
    call_id: str,
    current_user: dict = Depends(get_current_user)
):
    """
    获取通话信息
    
    Args:
        call_id: 通话ID
        current_user: 当前用户信息
        
    Returns:
        通话信息
    """
    try:
        call_info = voice_call_manager.get_call_info(call_id)
        if not call_info:
            raise HTTPException(status_code=404, detail="通话不存在")
        
        # 检查用户是否在通话中
        if current_user["user_id"] not in call_info["connected_users"]:
            raise HTTPException(status_code=403, detail="无权限查看此通话信息")
        
        return {
            "success": True,
            "call_info": call_info
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取通话信息失败: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"获取通话信息失败: {str(e)}")

@router.get("/call/{call_id}/users")
async def get_call_users(
    call_id: str,
    current_user: dict = Depends(get_current_user)
):
    """
    获取通话中的用户列表
    
    Args:
        call_id: 通话ID
        current_user: 当前用户信息
        
    Returns:
        用户列表
    """
    try:
        call_info = voice_call_manager.get_call_info(call_id)
        if not call_info:
            raise HTTPException(status_code=404, detail="通话不存在")
        
        # 检查用户是否在通话中
        if current_user["user_id"] not in call_info["connected_users"]:
            raise HTTPException(status_code=403, detail="无权限查看此通话用户")
        
        users = voice_call_manager.get_call_users(call_id)
        
        return {
            "success": True,
            "users": users,
            "total_users": len(users)
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取通话用户失败: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"获取通话用户失败: {str(e)}")

@router.websocket("/call/ws/{call_id}")
async def voice_call_websocket(
    websocket: WebSocket,
    call_id: str = Path(..., description="通话ID"),
    user_id: str = Query(..., description="用户ID")
):
    """
    语音电话WebSocket连接端点
    
    Args:
        websocket: WebSocket连接对象
        call_id: 通话ID（路径参数）
        user_id: 用户ID（查询参数）
    """
    await voice_call_service.handle_voice_call_connection(websocket, call_id, user_id)

@router.post("/transcribe")
async def transcribe_audio(
    audio_data: str,  # base64编码的音频数据
    language: str = "zh-CN",
    current_user: dict = Depends(get_current_user)
):
    """
    语音转文本API
    
    Args:
        audio_data: base64编码的音频数据
        language: 语言代码
        current_user: 当前用户信息
        
    Returns:
        识别结果
    """
    try:
        from src.services.voice_service import voice_service
        import base64
        
        # 解码base64音频数据
        audio_bytes = base64.b64decode(audio_data)
        
        # 语音转文本
        text, metadata = await voice_service.speech_to_text(audio_bytes, language)
        
        logger.info(f"语音转文本成功: 用户 {current_user['user_id']}, 长度: {len(text)}")
        
        return {
            "success": True,
            "text": text,
            "metadata": metadata
        }
        
    except Exception as e:
        logger.error(f"语音转文本失败: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"语音转文本失败: {str(e)}")

@router.post("/synthesize")
async def synthesize_speech(
    text: str,
    language: str = "zh-CN",
    voice: str = "zh-CN-XiaoxiaoNeural",
    current_user: dict = Depends(get_current_user)
):
    """
    文本转语音API
    
    Args:
        text: 要转换的文本
        language: 语言代码
        voice: 语音名称
        current_user: 当前用户信息
        
    Returns:
        音频数据（base64编码）
    """
    try:
        from src.services.voice_service import voice_service
        import base64
        
        # 文本转语音
        audio_data, metadata = await voice_service.text_to_speech(text, language, voice)
        
        # 编码为base64
        audio_base64 = base64.b64encode(audio_data).decode('utf-8')
        
        logger.info(f"文本转语音成功: 用户 {current_user['user_id']}, 文本长度: {len(text)}")
        
        return {
            "success": True,
            "audio_data": audio_base64,
            "metadata": metadata
        }
        
    except Exception as e:
        logger.error(f"文本转语音失败: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"文本转语音失败: {str(e)}")

@router.get("/health")
async def voice_service_health():
    """
    语音服务健康检查
    
    Returns:
        服务状态
    """
    try:
        from src.services.voice_service import voice_service
        
        # 简单的健康检查
        test_text = "语音服务健康检查"
        audio_data, _ = await voice_service.text_to_speech(test_text, "zh-CN")
        
        return {
            "success": True,
            "status": "healthy",
            "message": "语音服务运行正常",
            "audio_length": len(audio_data) if audio_data else 0
        }
        
    except Exception as e:
        logger.error(f"语音服务健康检查失败: {e}", exc_info=True)
        return {
            "success": False,
            "status": "unhealthy",
            "message": f"语音服务异常: {str(e)}"
        }
